/*=============================================================================
#     FileName: db.cpp
#         Desc: DB类的定义，该类封装了对mysql的访问
#       Author: Ace
#        Email: goace@acm.org
#     HomePage: http://www.goace.co.cc
#      Version: 0.0.1
#   LastChange: 2011-03-29 14:59:30
#      History:
=============================================================================*/

#include  <stdio.h>
#include  <iostream>
#include  <unistd.h>
#include  <cstdlib>
#include  <cstring>
#include  <mysql.h>
#include  "db.h"
using namespace std;

/* ---------------------------------------------------------------*/
/**
 * 函数简介:  检查用户名密码是否合法
 *
 * 参数: name 用户名
 * 参数: pwd  密码
 *
 * 返回值:   -1表示密码错误 -2表示用户名不存在
 *           -3表示未知错误  0表示登录成功
 */
/* ---------------------------------------------------------------*/
int DB::log_in(const char* name, const char* pwd)
{
	string cmd = "SELECT pwd FROM usr_info where usr_name = '";
	cmd += name;
	cmd += "'";

	int res = mysql_query(db,cmd.c_str());
	if( res )
	{
		cerr << "select error: " << mysql_error(db) << endl;
		return -3;
	}

	MYSQL_RES * result = mysql_store_result(db);
	if( result == NULL )
	{
		cerr << "mysql_store_result error" << endl;
		return -3;	
	}

	//查看用户名是否存在
	if( mysql_num_rows(result) == 0 )
	{
		return -2;
	}

	//查看密码是否正确
	MYSQL_ROW row = mysql_fetch_row(result);
	if( strcmp(pwd,row[0]) != 0 )
	{
		return -1;
	}

	return 0;
}

/* ---------------------------------------------------------------*/
/**
 * 函数简介:  连接数据库
 *
 * 返回值:   -1表明init失败  -2表示连接数据库失败 0表示初始化成功
 */
/* ---------------------------------------------------------------*/
int DB::init()
{
	db = mysql_init(NULL);
	if( !db )
	{
		cerr << "mysql_init failed:" << endl;
		return -1;
	}

	if( mysql_real_connect(db,"localhost",
				NULL,"clotshabby","gsync",0,NULL,0) == NULL ) 
	{
		cerr << "sql connect failed: " << mysql_error(db) <<  endl;
		return -2;
	}

	return 0;
}

DB::~DB()
{
	mysql_close(db);
}

/* ---------------------------------------------------------------*/
/**
 * 函数简介:  把新用户加入数据库 
 *
 * 参数: name 用户名
 * 参数: pwd  密码
 *
 * 返回值:   -1表示插入失败  0表示成功
 */
/* ---------------------------------------------------------------*/
int DB::add_usr(const char* name, const char* pwd)
{
	string cmd = "INSERT INTO usr_info VALUES('";
	cmd += name;
	cmd += "' , '";
	cmd += pwd;
	cmd += "')";

	int res = mysql_query(db,cmd.c_str());
	if( res )
	{
		cerr << "sql insert failed: " << mysql_error(db) <<  endl;
		return -1;
	}

	return 0;
}

